package com.daikin.ktmustwrite.data.repository.request

import com.daikin.ktmustwrite.app.network.apiService
import com.daikin.ktmustwrite.app.util.CacheUtil
import com.daikin.ktmustwrite.data.model.bean.ApiPagerResponse
import com.daikin.ktmustwrite.data.model.bean.ApiResponse
import com.daikin.ktmustwrite.data.model.bean.AriticleResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext

val HttpRequestCoroutine: HttpRequestManger by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { HttpRequestManger() }

class HttpRequestManger {
    /**
     * 获取首页文章数据
     */
    suspend fun getHomeData(pageNo: Int): ApiResponse<ApiPagerResponse<ArrayList<AriticleResponse>>> {
        return withContext(Dispatchers.IO) {
            val data = async { apiService.getAritrilList(pageNo) }
            if (CacheUtil.isNeedTop() && pageNo == 0) {
                val topData = async { apiService.getTopAritrilList() }
                data.await().data.datas.addAll(0, topData.await().data)
                data.await()
            } else {
                data.await()
            }
        }
    }


    /**
     * 获取项目标题数据
     */
    suspend fun getProjectData(
        pageNo: Int, cid: Int, isNew: Boolean = false
    ): ApiResponse<ApiPagerResponse<ArrayList<AriticleResponse>>> {
        return if (isNew) {
            apiService.getProjecNewData(pageNo)
        } else {
            apiService.getProjecDataByType(pageNo, cid)
        }
    }

}